import React, { useState, useEffect, useRef } from 'react';
import dayjs from 'dayjs';
import { zhCN } from "date-fns/locale";
import { Calendar } from "@/components/ui/calendar";
import { formatAmount } from '@/lib/tools';
export default function ({ netIncomeStatistics, bookId, accountNo, tags, onMonthChange, onDateChange }) {
    const [filterValue, setFilterValue] = useState({
        month: dayjs().format('YYYY-MM'),
        day: dayjs().format('YYYY-MM-DD'),
    });

    useEffect(() => {
        onMonthChange(filterValue.month);
        onDateChange(filterValue.day);
    }, []);
    return (
        <Calendar
            mode="single"
            locale={zhCN}
            selected={dayjs(filterValue.day, 'YYYY-MM-DD').toDate()}
            onMonthChange={value => {
                const month = dayjs(value).format('YYYY-MM');
                filterValue.month = month;

                if (filterValue.day.indexOf(filterValue.month) < 0) {
                    // 日期不在月份中
                    const filterDate = dayjs(`${month}-01`, 'YYYY-MM-DD');
                    const lastDayOfMonth = filterDate.endOf('month').startOf('day');
                    filterValue.day = lastDayOfMonth.format('YYYY-MM-DD');
                    onDateChange?.(filterValue.day);
                }

                onMonthChange?.(filterValue.month);
                setFilterValue({...filterValue});
            }}
            onSelect={value => {
                const day = dayjs(value).format('YYYY-MM-DD');
                setFilterValue({ ...filterValue, ...{ day: day } });
                onDateChange?.(day);
            }}
            components={{
                DayContent: props => {
                    const dayStr = dayjs(props.date).format('YYYY-MM-DD');
                    const items = (netIncomeStatistics || []).filter(stat => stat.days === dayStr);
                    const incomeItem = items.find(item => item.trans_type === '收入');
                    const expenseItem = items.find(item => item.trans_type === '支出');
                    const amount = (incomeItem?.trans_amount || 0) - (expenseItem?.trans_amount || 0);
                    return <div>
                        <div>{props.date.getDate()}</div>
                        <div className="text-xs">{amount !== 0 ? <div className={amount > 0 ? 'text-green-900' : 'text-red-900'}><span>{amount > 0 ? '+' : '-'}{formatAmount(amount)}</span></div>
                            : <div className="text-gray-200"><span>-</span></div>
                        }</div>
                    </div>
                }
            }}
            className="rounded-md border"
        />
    )
}
